import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Hashtable;

import org.parosproxy.paros.network.HttpMessage;


class Record {

	public Record() {

	}

	public Record(String id, String folder) {
		init(id, folder);
	}

	private void init(String id, String folder) {

		this.id = id;

		//load request header
		String requestHeaderFile = folder + id + "_request.txt";
		String requestHeader = Util.getFileData(requestHeaderFile);

		//load request post 
		String requestPostFile = folder + id + "_request_post.txt";
		Hashtable posts = Util.getHashdata(requestPostFile);

		//load response header
		String responseHeaderFile = folder + id + "_response.txt";
		String responseHeader = Util.getFileData(responseHeaderFile);

		//load response body
		String responseBodyFile = folder + id + "_response.html";
		String responseBody = Util.getFileData(responseBodyFile);

		msg = new HttpMessage();
		try {
			msg.getRequestHeader().setMessage(requestHeader);
			msg.getRequestBody().setBody(getRequestPostsAsString(posts));
			msg.getRequestHeader().setContentLength(
					msg.getRequestBody().length());
			msg.getResponseHeader().setMessage(responseHeader);
			msg.getResponseBody().setBody(responseBody);
			msg.getResponseHeader().setContentLength(
					msg.getResponseBody().length());
		} catch (Exception me) {
			me.printStackTrace();
		}

	}

	private String getRequestPostsAsString(Hashtable hash) {
		StringBuffer sb = new StringBuffer();
		Enumeration keys = hash.keys();
		boolean first = true;
		while (keys.hasMoreElements()) {
			if (!first)
				sb.append('&');
			first = false;
			String key = (String) keys.nextElement();
			String value = (String) hash.get(key);
			try {
				sb.append(URLEncoder.encode(key, "UTF8") + "="
						+ URLEncoder.encode(value, "UTF8"));
			} catch (UnsupportedEncodingException e) {
			} catch (IllegalArgumentException e) {
			}
		}
		return sb.toString();
	}

	public HttpMessage getHttpMessage() {
		return msg;
	}

	private String formatHeader(String msg) {
		String result = msg.replaceAll("\\n", "\r\n");
		result = result.replaceAll("(\\r\\n)*\\z", "") + "\r\n\r\n";
		return result;
	}

	public Record clone() {
		Record r = new Record();
		HttpMessage message = msg.cloneAll();
		r.msg = message;
		r.id = id;
		return r;
	}
	
	public String getId(){
		return id;
	}

	private String id = "";
	private HttpMessage msg = null;

}